# 题一

import numpy as np

samples_and = [
    [0, 0, 0],
    [1, 0, 0],
    [0, 1, 0],
    [1, 1, 1],
]
samples_or = [
    [0, 0, 0],
    [1, 0, 1],
    [0, 1, 1],
    [1, 1, 1],
]
samples_xor = [
    [0, 0, 0],
    [1, 0, 1],
    [0, 1, 1],
    [1, 1, 0],
]


def perception(samples):
    # 权重
    w = np.array([1, 2])
    # 偏置
    b = 0
    a = 1
    # 训练10遍
    for i in range(10):
        for j in range(4):
            # 矩阵的第j行的前两个数值
            x = np.array(samples[j][:2])
            # 将未激活的值输入sigmoid函数 dot:向量的点乘运算
            y = 1 if np.dot(w, x) + b > 0 else 0
            # 真实值
            d = np.array(samples[j][2])
            delta_b = a * (d - y)
            delta_w = a * (d - y) * x
            print('epoch {} sample [{} {} {} {} {} {} {}]'.format(
                i, j, w[0], w[1], b, y, delta_w[0], delta_w[1], delta_b
            ))
            # 反向传播，更新权重
            w = w + delta_w
            b = b + delta_b


if __name__ == '__main__':
    print('logical and：')
    perception(samples_and)
    print('logical or：')
    perception(samples_or)
    print('logical xor：')
    perception(samples_xor)
